package com.it.component;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollectionUtil;
import com.it.auth.LoginInfoDTO;
import com.it.bean.Menu;
import com.it.mapper.MenuMapper;
import com.it.mapper.UserMapper;
import com.it.vo.RoleVo;
import com.it.vo.UserVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author TBH
 * @date 2025-05-01 22:57:59
 * @desc 授权接口
 */
@Component
@RequiredArgsConstructor
public class StpInterfaceImpl implements StpInterface {
    private final UserMapper userMapper;
    private final MenuMapper menuMapper;
    private final AuthorizationCache authorizationCache;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        List<String> cachePermissions = authorizationCache.getPermissions(loginId);
        if (CollectionUtil.isNotEmpty(cachePermissions)) {
            return cachePermissions;
        }
        LoginInfoDTO loginInfoDTO = new LoginInfoDTO();
        loginInfoDTO.setUserId(Long.valueOf((String) loginId));
        UserVo user = userMapper.findUser(loginInfoDTO);
        List<RoleVo> roles = user.getRoles();
        List<Long> roleIds = roles.stream().map(RoleVo::getId).collect(Collectors.toList());
        List<Menu> menus = menuMapper.selectForRoles(roleIds);
        List<String> permissionCodes = menus.stream().map(Menu::getAuthority).collect(Collectors.toList());
        authorizationCache.setPermissions(loginId, permissionCodes);
        return permissionCodes;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<String> cacheRoles = authorizationCache.getRoles(loginId);
        if (CollectionUtil.isNotEmpty(cacheRoles)) {
            return cacheRoles;
        }
        LoginInfoDTO loginInfoDTO = new LoginInfoDTO();
        loginInfoDTO.setUserId(Long.valueOf((String) loginId));
        UserVo user = userMapper.findUser(loginInfoDTO);
        List<RoleVo> roles = user.getRoles();
        List<String> roleCodes = roles.stream().map(RoleVo::getCode).collect(Collectors.toList());
        authorizationCache.setRoles(loginId, roleCodes);
        return roleCodes;
    }
}